package com.caigou.modules.data.ui.data

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.adapter.CommentItemAdapter
import com.caigou.comm.base.adapter.PrizeBallItemAdapter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.CommentBean
import com.caigou.comm.base.bean.OpenPrizeVoBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.utils.MediaUtils
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.data.R
import com.caigou.modules.data.bean.DataDetailBean
import com.caigou.modules.data.databinding.ActivityDataDetailBinding
import com.caigou.modules.data.viewmodel.DataViewModel
import com.caigou.modules.data.viewmodel.LikeViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/29
 */
@Route(path = RouterPath.Data.PAGE_DATA_DETAIL)
@AndroidEntryPoint
class DataDetailActivity : BaseActivity() {

    private lateinit var binding: ActivityDataDetailBinding
    private val dataViewModel: DataViewModel by viewModels()
    private val likeViewModel: LikeViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.CATEGORY_ID)
    var categoryId = -1

    @JvmField
    @Autowired(name = AppConstants.CATEGORY_NAME)
    var categoryName = ""

    @JvmField
    @Autowired(name = AppConstants.DATA_ID)
    var dataId = -1

    private var page = 1
    private val limit = 10
    private var totalPage = 0
    private var sort = 0

    private val commentItemAdapter: CommentItemAdapter by lazy {
        CommentItemAdapter(mutableListOf())
    }

    private val prizeAdapter: PrizeBallItemAdapter by lazy {
        PrizeBallItemAdapter(mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDataDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.dataDetailLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        binding.dataDetailTvTitle.text = categoryName

        binding.dataDetailSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchDataDetail()
            }
        }

        commentItemAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                commentItemAdapter.loadMoreModule.isEnableLoadMore = true
                fetchCommentList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.dataDetailRecyclerViewComment.run {
            layoutManager = LinearLayoutManager(this@DataDetailActivity)
            adapter = commentItemAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@DataDetailActivity))
        }

        commentItemAdapter.setOnItemChildClickListener { _, view, position ->
            val item = commentItemAdapter.data[position]
            when (view.id) {
                R.id.item_comment_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.replyUserInfoVo.userId)
                        .navigation()
                }
                R.id.item_comment_ll_content -> {
                    ARouter.getInstance().build(RouterPath.Data.PAGE_COMMENT_DETAIL)
                        .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                        .withInt(AppConstants.DATA_TYPE, 3)
                        .navigation()
                }
                R.id.item_comment_iv_like -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        if (item.like) {
                            return@setOnItemChildClickListener
                        }
                        likeViewModel.setCommentLike(item.replyId, 3, AppBackgroundInfo.instance.userBean!!.userId, item.replyUserInfoVo.userId)
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
                R.id.item_comment_btn_reply -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        ARouter.getInstance()
                            .build(RouterPath.Data.PAGE_DATA_REPLY)
                            .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                            .withObject(AppConstants.COMMENT_ROOT_ITEM_BEAN, item)
                            .navigation()
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
            }
        }

        binding.dataDetailRgSelector.setOnCheckedChangeListener { group, _ ->
            sort = when (group.checkedRadioButtonId) {
                binding.dataDetailBtnSequential.id -> 1
                binding.dataDetailBtnReverse.id -> 0
                else -> 0
            }
            page = 1
            fetchCommentList()
        }

        binding.dataDetailTvBack.setOnClickListener {
            finish()
        }

        binding.dataDetailLlShare.setOnClickListener {
            val bitmap = binding.dataDetailLlContainer.screenCapture()
            MediaUtils.saveBitmap(this, bitmap)
            showToast("截图已保存到系统相册")
        }

        LiveDataBus.get().with(BusKey.REPLY_SUCCESS, Any::class.java).observe(this) {
            fetchCommentList()
        }

        fetchDataDetail()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(dataViewModel.dataDetailLiveData, ::handleGetDataDetail)
        observe(dataViewModel.commentListLiveData, ::handleGetCommentList)
        observe(likeViewModel.dataLikeLiveData, ::handleSetDataLike)
        observe(likeViewModel.commentLikeLiveData, ::handleSetCommentLike)
    }

    private fun handleGetDataDetail(result: Resource<DataDetailBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.dataDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.dataDetailSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    handleDetailUI(this)
                    fetchCommentList()
                }
            }
        }
    }

    private fun handleGetCommentList(result: Resource<CommentBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.dataDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取评论列表异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.dataDetailSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    binding.dataDetailLlEmptyComment.visibility = View.VISIBLE
                    binding.dataDetailRecyclerViewComment.visibility = View.GONE
                    return
                }
                if (result.data!!.list.isNullOrEmpty()) {
                    binding.dataDetailLlEmptyComment.visibility = View.VISIBLE
                    binding.dataDetailRecyclerViewComment.visibility = View.GONE
                } else {
                    binding.dataDetailLlEmptyComment.visibility = View.GONE
                    binding.dataDetailRecyclerViewComment.visibility = View.VISIBLE
                }

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    commentItemAdapter.setList(result.data!!.list)
                } else {
                    commentItemAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    commentItemAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    commentItemAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    commentItemAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun handleSetDataLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.dataDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.dataDetailSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    fetchDataDetail()
                }
            }
        }
    }

    private fun handleSetCommentLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.dataDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.dataDetailSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    fetchCommentList()
                }
            }
        }
    }

    private fun handleDetailUI(bean: DataDetailBean) {
        binding.dataDetailTvContentTitle.text = bean.title
        bean.content = bean.content.replace("\\r", "\r")
        bean.content = bean.content.replace("\\n", "\n")

        handlePrize(bean.openPrizeVo)

        binding.dataDetailTvContent.text = bean.content

        if (AppBackgroundInfo.instance.hasLogin) {
            if (TextUtils.isEmpty(AppBackgroundInfo.instance.userBean!!.headImg)) {
                binding.dataDetailIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this, AppBackgroundInfo.instance.userBean!!.headImg, binding.dataDetailIvMyAvatar)
            }
        } else {
            binding.dataDetailIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
        }

        binding.dataDetailTvLikeNum.text = bean.likeCount.toString()
        if (bean.like) {
            binding.dataDetailIvLike.setImageResource(R.drawable.img_data_like)
            binding.dataDetailTvLikeNum.setTextColor(Color.parseColor("#FE6880"))
        } else {
            binding.dataDetailIvLike.setImageResource(R.drawable.img_data_unlike)
            binding.dataDetailTvLikeNum.setTextColor(Color.parseColor("#505050"))
        }
        binding.dataDetailLlLike.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                if (bean.like) {
                    showToast("您已经点过赞了")
                } else {
                    likeViewModel.setDataLike(bean.mysteryId, 3, AppBackgroundInfo.instance.userBean!!.userId)
                }
            } else {
                showToast("请您先登录")
            }
        }

        binding.dataDetailTvCommentNum.text = bean.replyCount.toString()

        binding.dataDetailBtnReply.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Data.PAGE_DATA_REPLY)
                    .withInt(AppConstants.DATA_ID, bean.mysteryId)
                    .withInt(AppConstants.DATA_TYPE, 3)
                    .withString(AppConstants.RECEIVER_ID, "")
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }

        binding.dataDetailLlComment.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Data.PAGE_DATA_REPLY)
                    .withInt(AppConstants.DATA_ID, bean.mysteryId)
                    .withInt(AppConstants.DATA_TYPE, 3)
                    .withString(AppConstants.RECEIVER_ID, "")
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }
    }


    private fun handlePrize(bean: OpenPrizeVoBean) {
        if (bean.prizeList.isNullOrEmpty()) {
            binding.dataDetailTvPrizeTitle.visibility = View.GONE
            binding.dataDetailLlPrize.visibility = View.GONE
        } else {
            binding.dataDetailTvPrizeTitle.visibility = View.VISIBLE
            binding.dataDetailLlPrize.visibility = View.VISIBLE

            binding.dataDetailTvPrizeTitle.text = "第${bean.period}期开奖结果"
            binding.dataDetailRecyclerViewPrize.run {
                layoutManager = GridLayoutManager(this@DataDetailActivity, 6)
                adapter = prizeAdapter
                itemAnimator = DefaultItemAnimator()
                addItemDecoration(SpaceItemDecoration(this@DataDetailActivity))
            }

            val size = bean.prizeList.size
            val balls = bean.prizeList.slice(0..size - 2)
            prizeAdapter.setList(balls)
            val lastBall = bean.prizeList[size - 1]
            binding.dataDetailPrizeTvNum.text = lastBall.number
            binding.dataDetailPrizeTvNum.setBackgroundResource(prizeBallColor(lastBall.numberColor))
            binding.dataDetailPrizeTvDesc.text = lastBall.animalName

        }
    }

    private fun fetchDataDetail() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        dataViewModel.getDataDetail(categoryId, dataId, userId)
    }

    private fun fetchCommentList() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        dataViewModel.getCommentList(page, limit, dataId, sort, userId)
    }

}